<?php

namespace Lib\Pay;

use Mapper\OrderModel as OrderMapper;
use Mapper\MemberModel as MemberMapper;
use Mapper\SparringbuydetailModel as BuyDetailMapper;

class PayNotifyCallBack extends WxPayNotify {

    public function Queryorder($transaction_id) {
        $input = new WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = WxPayApi::orderQuery($input);
//        Log::DEBUG("query:" . json_encode($result));

        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS"
        ) {
            return true;
        }

        return false;
    }

    //重写回调处理函数
    public function NotifyProcess($data, &$msg) {
//        Log::DEBUG("call back:" . json_encode($data));
        $notfiyOutput = [];

        if(!array_key_exists("transaction_id", $data)) {
            $msg = "输入参数不正确";
            return false;
        }
        //查询订单，判断订单真实性
        if(!$this->Queryorder($data["transaction_id"])) {
            $msg = "订单查询失败";
            return false;
        }

        if(!array_key_exists("out_trade_no", $data)) {
            $msg = "商户订单号不正确";
            return false;
        }

        if(!array_key_exists("total_fee", $data)) {
            $msg = "总金额不正确";
            return false;
        }

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findByOrder_no($data['out_trade_no']);

        if(!$orderModel instanceof \OrderModel) {
            return false;
        }

        $status = $orderModel->getStatus();

        if($status !== \Lib\Consts::ORDER_STATUS_NOPAY) {
            return false;
        }

        $memberMapper = MemberMapper::getInstance();
        $memberModel  = $memberMapper->findById($orderModel->getTo_uid());

        if(!$memberModel instanceof \MemberModel) {
            return false;
        }

        $sellMemberModel = $memberMapper->findById($orderModel->getFrom_uid());

        if(!$sellMemberModel instanceof \MemberModel) {
            return false;
        }

        $buyDetailMapper = BuyDetailMapper::getInstance();
        $sparringNoArr   = explode(',', $orderModel->getSparring_no());
        $detailModels    = $buyDetailMapper->fetchAll(['id' => $sparringNoArr]);

        if(empty($detailModels)) {
            return false;
        }

        $timeInterval = '';

        foreach($detailModels as $detailModel) {
            $timeInterval .=
                date('H:i', $detailModel->getBegin_time()) . '-' . date('H:i', $detailModel->getEnd_time()) . ' ';
        }

        $buyData['time_interval']  = $timeInterval;
        $buyData['nickname']       = urldecode($sellMemberModel->getNick_name());
        $sellData['nickname']      = urldecode($memberModel->getNick_name());
        $sellData['date']          = date('Y年m月d日', $detailModels[0]->getBegin_time());
        $sellData['time_interval'] = $timeInterval;
        $sellData['price']         = $orderModel->getPay_price();
        $sellData['tel']           = $memberModel->getMobile();
        $orderId                   = $orderModel->getId();

        $orderData = [
            'status' => \Lib\Consts::ORDER_STATUS_PAY,
        ];

        $orderMapper->begin();

        try {
            $rows = $orderMapper->update($orderData, ['id' => $orderModel->getId(), 'status' => $status]);

            if($rows > 0) {
                \Lib\Queue::push('wxmsg', [
                    'touser'      => $memberModel->getOpen_id(),
                    'template_id' => \Lib\Consts::TEMP_ID_PAY_BUY,
                    'url'         => 'wx.dev.gaoqiapp.com/order_detail.html?order_id=' . $orderId . '&fund_flow=1',
                    'data'        => \Lib\Wechat::getInstance()->getTmp(\Lib\Consts::TEMP_ID_PAY_BUY, $buyData),
                ]);

                \Lib\Queue::push('wxmsg', [
                    'touser'      => $sellMemberModel->getOpen_id(),
                    'template_id' => \Lib\Consts::TEMP_ID_PAY_SELL,
                    'url'         => 'wx.dev.gaoqiapp.com/order_detail.html?order_id=' . $orderId . '&fund_flow=2',
                    'data'        => \Lib\Wechat::getInstance()->getTmp(\Lib\Consts::TEMP_ID_PAY_SELL, $sellData),
                ]);
            }
        } catch(\Exception $e) {
            $rows = 0;
        }

        if($rows <= 0) {
            $orderMapper->rollback();
            $msg = '订单状态变更失败';
            return false;
        }

        $payMapper = \Mapper\OrderPayModel::getInstance();
        $payModel  = new \OrderPayModel();
        $payModel->setOrder_id($orderId);
        $payModel->setPay_price($data['total_fee']);
        $payModel->setTransaction_id($data['transaction_id']);
        $payModel->setType(1);
        $payModel->setUid($orderModel->getFrom_uid());
        $payModel->setAdd_time($data['time_end']);

        try {
            $id = $payMapper->insert($payModel);
        } catch(\Exception $exc) {
            $id = 0;
        }

        if($id <= 0) {
            $orderMapper->rollback();
            $msg = '支付信息存储失败';
            return false;
        }

        $orderMapper->commit();
        return true;
    }

}